<template>
  <div class="property-form-preview">
    <div class="preview-header">
      <h4>动态表单预览</h4>
      <p class="preview-description">
        基于VbenForm的实时表单预览，展示真实的表单交互效果
      </p>
    </div>

    <div class="preview-content">
      <div class="schema-info">
        <h5>Schema信息</h5>
        <div class="schema-stats">
          <Tag color="blue">字段数量: {{ vbenSchema.length }}</Tag>
          <Tag color="green">必填字段: {{ requiredFieldsCount }}</Tag>
          <Tag color="orange">可选字段: {{ optionalFieldsCount }}</Tag>
        </div>
      </div>

      <div class="form-preview">
        <h5>实时表单预览</h5>
        <div class="form-container">
          <div v-if="vbenSchema.length > 0" class="form-fields">
            <div
              v-for="field in vbenSchema"
              :key="field.fieldName"
              class="form-field"
            >
              <div class="field-label">
                <span>{{ field.label }}</span>
                <Tag v-if="field.rules === 'required'" color="red" size="small"
                  >必填</Tag
                >
              </div>
              <div class="field-control">
                <Input
                  v-if="field.component === 'Input'"
                  v-model:value="formValues[field.fieldName]"
                  :placeholder="field.componentProps?.placeholder"
                  @change="handleFormChange"
                />
                <InputNumber
                  v-else-if="field.component === 'InputNumber'"
                  v-model:value="formValues[field.fieldName]"
                  :placeholder="field.componentProps?.placeholder"
                  :min="field.componentProps?.min"
                  :max="field.componentProps?.max"
                  @change="handleFormChange"
                />
                <Select
                  v-else-if="field.component === 'Select'"
                  v-model:value="formValues[field.fieldName]"
                  :placeholder="field.componentProps?.placeholder"
                  :options="field.componentProps?.options"
                  @change="handleFormChange"
                />
                <Switch
                  v-else-if="field.component === 'Switch'"
                  v-model:checked="formValues[field.fieldName]"
                  @change="handleFormChange"
                />
                <DatePicker
                  v-else-if="field.component === 'DatePicker'"
                  v-model:value="formValues[field.fieldName]"
                  :placeholder="field.componentProps?.placeholder"
                  @change="handleFormChange"
                />
                <Input.TextArea
                  v-else-if="field.component === 'Textarea'"
                  v-model:value="formValues[field.fieldName]"
                  :placeholder="field.componentProps?.placeholder"
                  :rows="4"
                  @change="handleFormChange"
                />
                <div v-else class="unsupported-component">
                  <IconifyIcon icon="ant-design:question-outlined" />
                  <span>不支持的组件类型: {{ field.component }}</span>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="no-schema">
            <IconifyIcon
              icon="ant-design:form-outlined"
              class="no-schema-icon"
            />
            <p>暂无可预览的表单字段</p>
            <p class="tip">请先配置属性Schema</p>
          </div>
        </div>
      </div>

      <div class="form-data">
        <h5>表单数据</h5>
        <div class="data-content">
          <pre>{{ JSON.stringify(formValues, null, 2) }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import {
  Tag,
  Input,
  InputNumber,
  Select,
  Switch,
  DatePicker,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

interface Props {
  schema?: any[];
  data?: Record<string, any>;
}

const props = withDefaults(defineProps<Props>(), {
  schema: () => [],
  data: () => ({}),
});

const emit = defineEmits<{
  'form-change': [values: Record<string, any>];
}>();

// 表单数据
const formValues = ref<Record<string, any>>({});

// 转换为预览Schema格式
const vbenSchema = computed(() => {
  if (!props.schema || !Array.isArray(props.schema)) return [];

  try {
    return props.schema
      .map((field: any) => {
        if (!field.fieldName || !field.component) return null;

        const schema = {
          fieldName: field.fieldName,
          label: field.label || field.fieldName,
          component: field.component,
          componentProps: {
            placeholder:
              field.componentProps?.placeholder || `请输入${field.label}`,
            ...field.componentProps,
          },
          rules: field.rules,
        };

        return schema;
      })
      .filter(Boolean);
  } catch (error) {
    console.error('生成预览Schema时出错:', error);
    return [];
  }
});

// 统计信息
const requiredFieldsCount = computed(() => {
  return props.schema.filter((field: any) => field.rules === 'required').length;
});

const optionalFieldsCount = computed(() => {
  return props.schema.filter((field: any) => field.rules !== 'required').length;
});

// 表单值变化处理
const handleFormChange = (values: Record<string, any>) => {
  formValues.value = { ...values };
  emit('form-change', values);
};

// 监听数据变化，初始化表单值
watch(
  () => props.data,
  (newData) => {
    if (newData && typeof newData === 'object') {
      formValues.value = { ...newData };
    }
  },
  { immediate: true, deep: true },
);

// 监听schema变化，重置表单
watch(
  () => props.schema,
  () => {
    // Schema变化时，保留现有数据
    formValues.value = { ...props.data };
  },
  { deep: true },
);
</script>

<style scoped>
.property-form-preview {
  padding: 20px;
}

.preview-header {
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-header h4 {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.preview-description {
  margin: 0;
  font-size: 14px;
  color: #8c8c8c;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.schema-info {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.schema-info h5 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.schema-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.form-preview {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.form-preview h5 {
  margin: 0 0 16px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.form-container {
  min-height: 200px;
  padding: 20px;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.form-fields {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-label {
  display: flex;
  gap: 8px;
  align-items: center;
  font-weight: 500;
  color: #262626;
}

.field-control {
  width: 100%;
}

.unsupported-component {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 8px 12px;
  font-size: 14px;
  color: #8c8c8c;
  background: #f5f5f5;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}

.no-schema {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #8c8c8c;
  text-align: center;
}

.no-schema-icon {
  margin-bottom: 16px;
  font-size: 48px;
  color: #d9d9d9;
}

.no-schema p {
  margin: 8px 0;
}

.tip {
  font-size: 12px;
  color: #bfbfbf;
}

.form-data {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.form-data h5 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.data-content {
  max-height: 200px;
  padding: 12px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.data-content pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
  color: #595959;
  word-break: break-all;
  white-space: pre-wrap;
}

/* VbenForm 样式覆盖 */
:deep(.vben-form) {
  .ant-form-item {
    margin-bottom: 16px;
  }

  .ant-form-item-label {
    font-weight: 500;
  }
}
</style>
